<template>
	<view>
		<view class="reg shadow-warp">
			<view class="text-black text-bold text-xl" style="text-align: center;padding: 20rpx 0;">用户注册</view>
			<view style="border-bottom: 5rpx #54b7f3 solid;"></view>

      <!--       用户注册        -->
      <view>
        <uv-form ref="form" :model="registerForm" :rules="rules" error-type="toast">
          <uv-form-item prop="tenantId">
            <uv-input v-model="currentTenantName" placeholder="请选择租户" readonly>
              <template #prefix>
                <uv-icon name="zuhu" custom-prefix="verulia-icon"></uv-icon>
              </template>
              <template #suffix>
                <uv-picker ref="tenantPicker" :columns="[tenantList]" key-name="companyName" round="15" @confirm="handleSelectTenant"></uv-picker>
                <uv-button text="选择租户" type="success" size="mini" @click="openTenantPicker"></uv-button>
              </template>
            </uv-input>
          </uv-form-item>
          <uv-form-item prop="username">
            <uv-input v-model="registerForm.username" prefix-icon="account" placeholder="请输入用户名" />
          </uv-form-item>
          <uv-form-item prop="password">
            <uv-input v-model="registerForm.password" :password="true" prefix-icon="lock" placeholder="请输入密码">
            </uv-input>
          </uv-form-item>
          <uv-form-item prop="confirmPassword">
            <uv-input v-model="registerForm.confirmPassword" :password="true" prefix-icon="lock" placeholder="请再次输入密码">
            </uv-input>
          </uv-form-item>
          <uv-form-item prop="phonenumber">
            <uv-input v-model="registerForm.phonenumber" prefix-icon="phone" placeholder="请输入手机号码" />
          </uv-form-item>
          <uv-form-item prop="code" v-if="captchaEnabled">
            <view style="display: flex">
              <view style="width: 63%;">
                <uv-input v-model="registerForm.code" type="number" prefix-icon="empty-permission" placeholder="请输入验证码" />
              </view>
              <view class="login-code">
                <img :src="codeUrl" class="login-code__img" @click="getCode" />
              </view>
            </view>
          </uv-form-item>
        </uv-form>
      </view>

      <!-- 用户注册 -->
      <view class="login-btn">
        <uv-button :loading="loading" type="primary" text="注册" @click="handleRegister"></uv-button>
      </view>
      <view>
        <uv-divider textColor="#2979ff" text="已有账号! 立即登录" @click="handleToLogin"></uv-divider>
      </view>

		</view>
	</view>
</template>

<script setup lang="ts">

import to from 'await-to-js';
import appConfig from '@/appConfig'
import { useUserStore } from '@/store/modules/user.store'
import { getCodeImg, getTenantList, register } from '@/api/auth.api'
import { TenantVO,RegisterForm } from '@/api/auth.type'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const userStore = useUserStore()

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);
// 租户列表
const tenantList = ref<TenantVO[]>([])
const tenantPicker = ref()
const currentTenantName = ref('')

const registerForm = ref<RegisterForm>({
  tenantId: '',
  username: '',
  password: '',
  confirmPassword: '',
  phonenumber: '',
  code: '',
  uuid: '',
  userType: 'app_user'
});

const form = ref();
const rules = ref({
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [
    { required: true, trigger: 'blur', message: '请输入您的账号' },
    { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入您的密码' },
    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
    { pattern: /^[^<>"'|\\]+$/, message: '不能包含非法字符：< > " \' \\\ |', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, trigger: 'blur', message: '请再次输入您的密码' },
    {
      validator: (rule, value, callback) => {return registerForm.value.password == value},
      message: '两次输入的密码不一致',
			trigger: ['blur', 'change']
    }
  ],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }],
  phonenumber: [
    { required: true, trigger: 'change', message: '请输入手机号' },
    {
      validator: (rule, value, callback) => {return uni.$uv.test.mobile(value)},
      message: '电话号码格式错误',
			trigger: ['blur', 'change']
    }
  ]
});

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    registerForm.value.uuid = data.uuid;
  }
};

/**
 * 获取租户列表
 */
/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList();
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      registerForm.value.tenantId = tenantList.value[0].tenantId
      currentTenantName.value = tenantList.value[0].companyName
    }
  }
};

const openTenantPicker = () => {
  tenantPicker.value.open()
}

const handleSelectTenant = (e: any) => {
  const { value } = e
  registerForm.value.tenantId = value[0].tenantId
  currentTenantName.value = value[0].companyName
}

const handleRegister = () => {
  form.value?.validate().then(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const [err] = await to(register(registerForm.value));
      if (!err) {
        const username = registerForm.value.username;
        await  proxy?.$modal.msgSuccess("恭喜你，您的账号"+ username + "注册成功！")
        await  proxy?.$tab.navigateTo('/pages/login')
      } else {
        loading.value = false;
        if (captchaEnabled.value) {
          getCode();
        }
      }
    }
  });
};

/** 跳转到登录页面 */
const handleToLogin = () => {
  proxy?.$tab.navigateTo('/pages/login')
}

onLoad(() => {
  getCode();
  initTenantList();
});

</script>

<style>
page {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-image: url('https://iot.qzxhdz.com:9021/static/image/backreg.png');
  background-repeat: no-repeat;
  min-height: 100%;
  background-size: cover;
  height: auto;
}
</style>

<style lang="scss" scoped>
.reg{
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  margin-top: 100rpx;
  border-radius: 25rpx;
  background-color: #fff;
  padding: 0 40rpx;
}

.button-group {
  width: 90%;
  margin: 0 auto;
}

.login-code {
  width: 35%;
  height: 38px;
  float: right;

  &__img {
    height: 38px;
    margin-left: 10px;
    width: 100px;
  }
}
</style>
